package com.lottery.ruok.lottrey.ui

import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.Editable
import android.text.Html
import android.text.TextWatcher
import android.view.View
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.SeekBar
import android.widget.TextView
import com.lottery.ruok.lottrey.R
import com.lottery.ruok.lottrey.activity.BaseActivity
import com.lottery.ruok.lottrey.adapter.LHCQuickAmountAdapter
import com.lottery.ruok.lottrey.adapter.LHCQuickEditAmountAdapter
import com.lottery.ruok.lottrey.bean.LHCQuickItem
import com.lottery.ruok.lottrey.common.Common
import com.lottery.ruok.lottrey.interfaces.LotteryShowStep
import com.lottery.ruok.lottrey.userInfo.UserInfo
import utils.Utils
import java.util.LinkedHashMap
import kotlin.collections.ArrayList

class BottomOrderLayout (baseActivity: BaseActivity,
                        randomAction: ()->Unit,
                        cancelAction: ()->Unit,
                        editChange: ()->Unit,
                        confirmAction: ()->Unit,
                        gotoShoppingCar: ()->Unit,
                        addNotesAction: ()->Unit,
                        fromOffical: Boolean,
                        refreshMoney: (()->Unit)?,
                        gotoLoginActivity: (()->Unit)?,
                        gotoSummaryActivity: ()->Unit)
    : LotteryShowStep {
    val account_1: View = baseActivity.findViewById(R.id.account_1)
    val account_2: View
    val account_step_1: View
    val account_step_2: View
    val include_account2: TextView
    val include_account: TextView
    val include_random: View
    val include_state1: View
    val include_state2: View
    val include_state3: View
    val fast_amout: RecyclerView
    val fast_amout_edit: RecyclerView
//    val group_minus: View
//    val group_add: View
    val edit_quick_amount: View
    val delete_edit: View
    val confirm_edit: View
    private var quickEditList: MutableList<String>? = null
    var quick_adapter: LHCQuickAmountAdapter? = null
    private var edit_adapter: LHCQuickEditAmountAdapter? = null
    val numAndMoney: TextView
    val money_and_num: EditText
    val confirm: TextView
    val delete: TextView
    val include_shop: View
    val include_note_count: TextView
    val peilv: TextView
    val add_order: View
    val include_divider: View
    val include_slider: LinearLayout
    val include_odd: TextView
    val include_rakeback: TextView
    val line: SeekBar
    val yuan: TextView
    val jiao: TextView
    val fen: TextView
    val money_unit: TextView
    val today_profit: TextView
    val login_tip: TextView
    var now_rakeback: String? = null
    private var unit_type: Int = 0
    var oddNumber: ArrayList<String> = ArrayList()
    var refreshOdds: ((ArrayList<String>)->Unit)? = null
    var fromOffical: Boolean
    var refreshMoney: (()->Unit)?

    fun initSlide(min_rakeback: Float = 0f,
                  max_rakeback: Float = 0f,
                  max_profit: Float = 0f,
                  min_profit: String? = null,
                  theory_odds: LinkedHashMap<String, String>? = null,
                  max_odds: LinkedHashMap<String, String>? = null,
                  layout_code: String? = null,
                  status2: String? = null){
        line.progress = 0

        include_rakeback.text = min_rakeback.toString() + "%"
        var r = 0
        var odds: String? = null
        oddNumber.clear()
        max_odds?.forEach {
            odds = if (r == 0) {
                it.value
            } else {
                odds + "|" + it.value
            }
            r++
            oddNumber.add(String.format("%.3f", java.lang.Float.parseFloat(it.value)))
        }
        include_odd.text = odds
        if(layout_code != null && layout_code == "hezhi_hezhi_hezhi"){
            include_odd.visibility = View.GONE
            peilv.visibility = View.GONE
        } else {
            include_odd.visibility = View.VISIBLE
            peilv.visibility = View.VISIBLE
        }

        if(status2 != null && status2 == "0"){
            line.isEnabled = false
        }

        now_rakeback = min_rakeback.toString() + ""

        line.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener{
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                now_rakeback = String.format("%.1f", min_rakeback + (max_rakeback - min_rakeback) * progress / 100.0)

                val site_profit: Float = if (min_profit == null) {
                    max_profit
                } else {
                    max_profit - (max_profit - java.lang.Float.parseFloat(min_profit)) * (java.lang.Float.parseFloat(now_rakeback) / (max_rakeback - min_rakeback))
                }
                var r = 0
                if (theory_odds != null) {
                    var odds: String? = null
                    for (th in theory_odds.keys) {
                        val nows = java.lang.Float.parseFloat(theory_odds[th]) * (1f - site_profit / 100.0f - java.lang.Float.parseFloat(now_rakeback) / 100.0f)
                        odds = if (r == 0) {
                            String.format("%.3f", nows)
                        } else {
                            odds + "|" + String.format("%.3f", nows)
                        }
                        oddNumber[r] = String.format("%.3f", nows)
                        r++
                    }
                    include_odd.text = odds
                }

                if(layout_code != null && layout_code == "hezhi_hezhi_hezhi"){
                    refreshOdds?.invoke(oddNumber)
                }

                include_rakeback.text = "$now_rakeback%"
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {

            }
            override fun onStopTrackingTouch(seekBar: SeekBar?) {

            }
        })
    }

    init {
        account_2 = baseActivity.findViewById(R.id.account_2)
        include_account = baseActivity.findViewById(R.id.include_account)
        include_random = baseActivity.findViewById(R.id.include_random)
        include_state1 = baseActivity.findViewById(R.id.include_state1)
        include_state2 = baseActivity.findViewById(R.id.include_state2)
        include_state3 = baseActivity.findViewById(R.id.include_state3)
        fast_amout = baseActivity.findViewById(R.id.fast_amout)
//        group_minus = baseActivity.findViewById(R.id.group_minus)
//        group_add = baseActivity.findViewById(R.id.group_add)
        fast_amout_edit = baseActivity.findViewById(R.id.fast_amout_edit)
        edit_quick_amount = baseActivity.findViewById(R.id.edit_quick_amount)
        delete_edit = baseActivity.findViewById(R.id.delete_edit)
        confirm_edit = baseActivity.findViewById(R.id.confirm_edit)
        include_account2 = baseActivity.findViewById(R.id.include_account2)
        account_step_1 = baseActivity.findViewById(R.id.account_step_1)
        account_step_2 = baseActivity.findViewById(R.id.account_step_2)
        numAndMoney = baseActivity.findViewById(R.id.numAndMoney)
        money_and_num = baseActivity.findViewById(R.id.money_and_num)
        confirm = baseActivity.findViewById(R.id.confirm)
        delete = baseActivity.findViewById(R.id.delete)
        peilv = baseActivity.findViewById(R.id.peilv)
        include_shop = baseActivity.findViewById(R.id.include_shop)
        include_note_count = baseActivity.findViewById(R.id.include_note_count)
        add_order = baseActivity.findViewById(R.id.add_order)
        include_divider = baseActivity.findViewById(R.id.include_divider)
        include_slider = baseActivity.findViewById(R.id.include_slider)
        include_odd = baseActivity.findViewById(R.id.include_odd)
        include_rakeback = baseActivity.findViewById(R.id.include_rakeback)
        line = baseActivity.findViewById(R.id.line)
        yuan = baseActivity.findViewById(R.id.yuan)
        jiao = baseActivity.findViewById(R.id.jiao)
        fen = baseActivity.findViewById(R.id.fen)
        money_unit = baseActivity.findViewById(R.id.money_unit)
        login_tip = baseActivity.findViewById(R.id.login_tip)
        today_profit = baseActivity.findViewById(R.id.today_profit)
        this.fromOffical = fromOffical
        this.refreshMoney = refreshMoney

        if(fromOffical){
            include_divider.visibility = View.VISIBLE
            include_slider.visibility = View.VISIBLE
            setUnit()
        }

        setLoginState()

        add_order.setOnClickListener {//清空金额和快捷选择
            addNotesAction.invoke()

            money_and_num.setText("")
        }

        confirm.setOnClickListener {//清空金额和快捷选择
            confirmAction.invoke()

            money_and_num.setText("")
        }

        include_shop.setOnClickListener {
            gotoShoppingCar.invoke()
        }

        login_tip.setOnClickListener {
            gotoLoginActivity?.invoke()
        }

        today_profit.setOnClickListener {
            gotoSummaryActivity.invoke()
        }

        delete.setOnClickListener {
            if(delete.text == "清空"){//把金钱设置为0
                money_and_num.setText("")
            } else if(delete.text == "取消"){//返回第一步，把所有已经选中的全部恢复
                cancelAction.invoke()
            }
        }

        money_and_num.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(p0: Editable?) {
                setDeleteText()

                editChange.invoke()

                //改变输入框里的值与上面的快捷选项相匹配
                quick_adapter?.getLHCQuickItems()?.let {
                    for(i in quick_adapter?.getLHCQuickItems().orEmpty()){
                        i.isChoose = (p0.toString() == i.number)
                    }
                }
                quick_adapter?.notifyDataSetChanged()

                money_and_num.requestFocus()
            }

            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }
        })

        include_random.setOnClickListener {
            randomAction.invoke()
        }

//        group_minus.setOnClickListener {
//            quickEditList?.removeAt(0)
//
//            setAddOrMinusShow(baseActivity)
//        }
//        group_add.setOnClickListener {
//            quickEditList?.add("")
//
//            setAddOrMinusShow(baseActivity)
//        }
        edit_quick_amount.setOnClickListener {
            if(fromOffical){
                if(quickEditList == null){
                    val tempList: String = UserInfo.getQuickAmountYJF()
                    quickEditList = tempList.split(";").toMutableList()
                } else {
                    quickEditList?.let {
                        it.clear()
                        val tempList: String = UserInfo.getQuickAmountYJF()
                        it.addAll(tempList.split(";").toMutableList())
                    }
                }
            } else {
                if(quickEditList == null){
                    quickEditList = UserInfo.getQuickAmount().split(";").toMutableList()
                } else {
                    quickEditList?.let {
                        it.clear()
                    it.addAll(UserInfo.getQuickAmount().split(";").toMutableList())
                    }
                }
            }

            setAddOrMinusShow(baseActivity)

            bottomShowState3()
        }
        delete_edit.setOnClickListener {
            bottomShowState2()
        }
        confirm_edit.setOnClickListener {
            //点击确定才会保存在本地，如果有空值或者0，那么就提示用户
            quickEditList?.let {
                for (i in it.indices){
                    if (it[i].isEmpty() || it[i].toInt() == 0){
                        Utils.showToast("请输入快捷金额")
                        return@let
                    }
                }
                //存储到本地
                if(fromOffical){
                    var temp: String? = null
                    for (i in it.indices){
                        temp = if (temp == null){
                            it[i]
                        } else {
                            temp + ";" + it[i]
                        }
                    }
                    UserInfo.setQuickAmountYJF(temp)

                    refreshMoney?.invoke()
                } else {
                    var temp: String? = null
                    for (i in it.indices){
                        temp = if (temp == null){
                            it[i]
                        } else {
                            temp + ";" + it[i]
                        }
                    }
                    UserInfo.setQuickAmount(temp)
                }

                setQuickAmountList(baseActivity)

                bottomShowState2()
            }
        }

        setQuickAmountList(baseActivity)
    }

    private fun setUnit(){
        val unit: String = UserInfo.getQuickAmountUnit()
        if(unit == "元"){
            setYuan()
        } else if(unit == "角"){
            setJiao()
        } else if(unit == "分"){
            setFen()
        }
        yuan.setOnClickListener {
            setYuan()
            UserInfo.setQuickAmountUnit("元")
            refreshMoney?.invoke()
        }
        jiao.setOnClickListener {
            setJiao()
            UserInfo.setQuickAmountUnit("角")
            refreshMoney?.invoke()
        }
        fen.setOnClickListener {
            setFen()
            UserInfo.setQuickAmountUnit("分")
            refreshMoney?.invoke()
        }
    }

    fun returnMoney(): Int{
        return if (money_and_num.text.isEmpty()) 0 else money_and_num.text.toString().toInt()
    }

    fun returnUnit(): Float{
        return if (unit_type == 0) 1f else if (unit_type == 1) 0.1f else 0.01f
    }

    private fun setYuan(){
        unit_type = 0
        money_unit.text = "元"
        yuan.setBackgroundResource(R.mipmap.mini_bing)
        jiao.setBackgroundResource(R.mipmap.mini_bing2)
        fen.setBackgroundResource(R.mipmap.mini_bing2)
    }

    private fun setJiao(){
        unit_type = 1
        money_unit.text = "角"
        yuan.setBackgroundResource(R.mipmap.mini_bing2)
        jiao.setBackgroundResource(R.mipmap.mini_bing)
        fen.setBackgroundResource(R.mipmap.mini_bing2)
    }

    private fun setFen(){
        unit_type = 2
        money_unit.text = "分"
        yuan.setBackgroundResource(R.mipmap.mini_bing2)
        jiao.setBackgroundResource(R.mipmap.mini_bing2)
        fen.setBackgroundResource(R.mipmap.mini_bing)
    }

    private fun setQuickAmountList(baseActivity: BaseActivity){
        if(fromOffical){
            val linearLayoutManager = LinearLayoutManager(baseActivity, LinearLayoutManager.HORIZONTAL, false)
            fast_amout.layoutManager = linearLayoutManager
            val split_array: String = UserInfo.getQuickAmountYJF()
            val temp: List<String> = split_array.split(";")
            val temp_list: MutableList<LHCQuickItem> = mutableListOf()
            for(i in temp.indices){
                val lhcQuickItem = LHCQuickItem(temp[i], money_and_num.text.toString() == temp[i])
                temp_list.add(lhcQuickItem)
            }
            quick_adapter = LHCQuickAmountAdapter(temp_list){
                money_and_num.setText(it)
                for(i in temp.indices){
                    temp_list[i].isChoose = (it == temp_list[i].number)
                }
                quick_adapter?.notifyDataSetChanged()
            }
            fast_amout.adapter = quick_adapter
        } else {
            val linearLayoutManager = LinearLayoutManager(baseActivity, LinearLayoutManager.HORIZONTAL, false)
            fast_amout.layoutManager = linearLayoutManager
            val temp: List<String> = UserInfo.getQuickAmount().split(";")
            val temp_list: MutableList<LHCQuickItem> = mutableListOf()
            for(i in temp.indices){
                val lhcQuickItem = LHCQuickItem(temp[i], money_and_num.text.toString() == temp[i])
                temp_list.add(lhcQuickItem)
            }
            quick_adapter = LHCQuickAmountAdapter(temp_list){
                money_and_num.setText(it)
                for(i in temp.indices){
                    temp_list[i].isChoose = (it == temp_list[i].number)
                }
                quick_adapter?.notifyDataSetChanged()
            }
            fast_amout.adapter = quick_adapter
        }
    }

    private fun setAddOrMinusShow(baseActivity: BaseActivity) {
//        if (quickEditList?.size == 5) {
//            group_add.visibility = View.INVISIBLE
//            group_minus.visibility = View.VISIBLE
//        } else if (quickEditList?.size == 1) {
//            group_add.visibility = View.VISIBLE
//            group_minus.visibility = View.INVISIBLE
//        } else {
//            group_add.visibility = View.VISIBLE
//            group_minus.visibility = View.VISIBLE
//        }

        quickEditList?.let {
            if (edit_adapter == null) {
                val linearLayoutManagerEdit = LinearLayoutManager(baseActivity, LinearLayoutManager.HORIZONTAL, false)
                fast_amout_edit.layoutManager = linearLayoutManagerEdit
                edit_adapter = LHCQuickEditAmountAdapter(it, { k, v ->
                    quickEditList?.let {
                        if(v < it.size){
                            it[v] = k
                        }
                    }
                })
                fast_amout_edit.adapter = edit_adapter
            } else {
            edit_adapter?.notifyDataSetChanged()
            }
        }
    }

    fun setLoginState(){
        if(UserInfo.getToken() == ""){
            account_1.visibility = View.GONE
            account_2.visibility = View.GONE
            include_account.visibility = View.GONE
            account_step_1.visibility = View.INVISIBLE
            account_step_2.visibility = View.INVISIBLE
            include_account2.visibility = View.INVISIBLE
            login_tip.visibility = View.VISIBLE
            today_profit.visibility = View.GONE
        } else {
            account_1.visibility = View.VISIBLE
            account_2.visibility = View.VISIBLE
            include_account.visibility = View.VISIBLE
            account_step_1.visibility = View.VISIBLE
            account_step_2.visibility = View.VISIBLE
            include_account2.visibility = View.VISIBLE
            login_tip.visibility = View.GONE
            today_profit.visibility = View.VISIBLE

            include_account.text = UserInfo.getAccount()
            include_account2.text = UserInfo.getAccount()
            if(Common.today_profit != null && !Common.today_profit.equals("")){
                if(Utils.isNumeric(Common.today_profit)){
                    val profit = Common.today_profit.toFloat()
                    if(profit > 0){
                        today_profit.text = Html.fromHtml("<u>今日输赢</u>：<font color='#ff6c2c'>$profit</font><font color='#9d9d9d'>元</font>")
                    } else {
                        today_profit.text = Html.fromHtml("<u>今日输赢</u>：<font color='#7eb379'>$profit</font><font color='#9d9d9d'>元</font>")
                    }
                }
            }
        }
    }

    private fun setStep1Visible(visible: Boolean){//设置第一步含有摇动机选的那个是否可见
        include_state1.visibility = if (visible) View.VISIBLE else View.GONE
    }

    private fun setStep2Visible(visible: Boolean){//设置第二步下单那个是否可见
        include_state2.visibility = if (visible) View.VISIBLE else View.GONE
    }

    private fun setStep3Visible(visible: Boolean){//设置第三步编辑快捷金额那个是否可见
        include_state3.visibility = if (visible) View.VISIBLE else View.GONE
    }

    fun setDeleteText(){
        if(money_and_num.text.isEmpty()){
            delete.text = "取消"
        } else {
            delete.text = "清空"
        }
    }

    override fun bottomShowState1() {
        setStep1Visible(true)
        setStep2Visible(false)
        setStep3Visible(false)
    }

    override fun bottomShowState2() {
        setDeleteText()

        if(fromOffical){
            setUnit()
        }

        setStep1Visible(false)
        setStep2Visible(true)
        setStep3Visible(false)
    }

    override fun bottomShowState3() {
        setStep1Visible(false)
        setStep2Visible(false)
        setStep3Visible(true)
    }
   fun bottomShowState4() {
        setStep1Visible(false)
        setStep2Visible(false)
        setStep3Visible(false)
    }
}